import { TBill } from '@/types';
import { PlusIcon } from '@/components/icons';
import { FixedBtn, RadioIconButton } from '@/components';
import { useQuery } from 'react-query';
import { request } from '@/request';
import { toLocalTime, getSum } from '@/utils';
import { useHistory } from 'react-router-dom';
import { useGlobalVar } from '@/hooks';
import { useState, useMemo } from 'react';
import { TOption } from '@/components/RadioIconButton';
import BillCard from './BillCard';
import BillSelfCard from './BillSelfCard';
import _ from 'lodash';

const getSpend = (bills: Array<TBill>, filter) => {
   let allAccounts = [];
   bills.forEach((bill) => {
      if (filter === 'myself') {
         bill.filterdDetails.forEach((detail) => {
            allAccounts.push(detail.account);
         });
      } else {
         allAccounts.push(bill.account);
      }
   });
   return getSum(allAccounts);
};

const options: Array<TOption> = [
   {
      value: 'all',
      icon: 'all',
      label: '全部',
   },
   {
      value: 'myself',
      icon: 'user',
      label: '与我相关',
   },
];

const BillsList = () => {
   const { groupId, user } = useGlobalVar();
   const [filter, setFilter] = useState('all');

   const { data } = useQuery(
      `bills${groupId}`,
      async () => request(`/bills/byGroup/${groupId}`),
      {
         enabled: !!groupId,
      }
   );

   const history = useHistory();
   const handleDetail = (billId: string) => {
      history.push(`/bill-detail/${billId}`);
   };
   const handleChangeFilter = (value) => {
      setFilter(value);
   };

   if (!groupId) return <div>暂无数据</div>;
   if (!data) return <div>loading...</div>;
   let bills = data.data as Array<TBill>;

   // 过滤与调整格式
   const isSeftRelated = filter === 'myself';
   if (isSeftRelated) {
      bills = bills.filter((item) =>
         item.members.map((user) => user._id).includes(user._id)
      );
   }

   let formatterd = Object.entries(
      bills.reduce((acc, bill) => {
         const day = toLocalTime(bill.createdAt, 'YYYY-MM-DD');
         if (!acc[day]) {
            acc[day] = [];
         }
         if (isSeftRelated) {
            bill.filterdDetails = bill.details.filter(
               (item) => item.userId === user._id
            );
         } else {
            bill.filterdDetails = _.clone(bill.details);
         }
         acc[day].push(bill);
         return acc;
      }, {}) as { [key: string]: Array<TBill> }
   );

   return (
      <div>
         {/* 总支出 */}
         <div className="mt-6 mb-4 text-sm flex justify-between">
            <RadioIconButton
               value={filter}
               options={options}
               onChange={handleChangeFilter}
            />
            <span className="flex items-center space-x-1">
               <span>总支出：{getSpend(bills, filter)}</span>
            </span>
         </div>
         <div className="space-y-3">
            {formatterd.length === 0
               ? '暂无账单'
               : formatterd.map(([key, item]) => {
                    let accounts = [];

                    item.forEach((bill) =>
                       accounts.push(
                          ...bill.filterdDetails.map((item) => item.account)
                       )
                    );

                    return (
                       <div key={key}>
                          {/* 每天总结 */}
                          <div className="color-disabled text-xs flex justify-between">
                             <span>{key}</span>
                             <span>支出: {getSum(accounts)}</span>
                          </div>
                          {/* 每天详情 */}
                          <div className="flex flex-col gap-2 mt-1 text-xs">
                             {item.map((bill) =>
                                isSeftRelated ? (
                                   <BillSelfCard
                                      data={bill}
                                      key={bill._id}
                                      onClick={handleDetail}
                                   />
                                ) : (
                                   <BillCard
                                      data={bill}
                                      key={bill._id}
                                      onClick={handleDetail}
                                   />
                                )
                             )}
                          </div>
                       </div>
                    );
                 })}
         </div>

         <FixedBtn
            onClick={() => {
               history.push('/bill');
            }}
         >
            <PlusIcon type="white" />
         </FixedBtn>
      </div>
   );
};

export default BillsList;
